package com.hjt.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hjt.common.constant.WareConstant;
import com.hjt.common.utils.PageUtils;
import com.hjt.common.utils.Query;
import com.hjt.gulimall.ware.dao.PurchaseDao;
import com.hjt.gulimall.ware.entity.PurchaseDetailEntity;
import com.hjt.gulimall.ware.entity.PurchaseEntity;
import com.hjt.gulimall.ware.entity.WareSkuEntity;
import com.hjt.gulimall.ware.service.PurchaseDetailService;
import com.hjt.gulimall.ware.service.PurchaseService;
import com.hjt.gulimall.ware.service.WareSkuService;
import com.hjt.gulimall.ware.vo.MergeVo;
import com.hjt.gulimall.ware.vo.PurchaseFinishedVo;
import com.hjt.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 分页查询未领取的采购单信息
     * @param params
     * @return
     */
    @Override
    public PageUtils queryUnReceivedList(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        // 查询状态为 新建 或 未领取 的采购单
        wrapper.in("status", WareConstant.PurchaseStatusEnum.NEW_STATUS.getCode(),
                                           WareConstant.PurchaseStatusEnum.ALLOCATED_STATUS);

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }

    /**
     * 合并采购需求为一个采购单
     */
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        // TODO:确认采购单状态为0才可以合并
        // id为空新建采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.NEW_STATUS.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        } else {
            // 不为空设置修改时间
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }
        // 生成采购需求实体类列表
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = mergeVo.getItems().stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ALLOCATED_STATUS.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        // 批量修改采购需求状态
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
    }

    /**
     * 领取采购单
     * @param ids
     */
    @Transactional
    @Override
    public void received(List<Long> ids) {
        // 确认采购单是新建或者以分配状态
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(purchaseId -> {
            return getById(purchaseId);
        }   ).filter(purchaseEntity ->
                purchaseEntity.getStatus().equals(WareConstant.PurchaseStatusEnum.NEW_STATUS.getCode()) ||
                        purchaseEntity.getStatus().equals(WareConstant.PurchaseStatusEnum.ALLOCATED_STATUS.getCode())
        ).peek(purchaseEntity -> {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.PURCHASING_STATUS.getCode());
        }).collect(Collectors.toList());

        if (purchaseEntityList.size() > 0) {
            // 修改采购单状态
            this.updateBatchById(purchaseEntityList);
        }

        // 修改采购需求状态
        ids.forEach(purchaseId -> {
            // 获取采购单下的所有采购需求
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailService.listByPurchaseId(purchaseId);
            // 修改状态
            purchaseDetailEntityList.forEach(purchaseDetailEntity -> {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.PURCHASING_STATUS.getCode());
            });
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });
    }

    /**
     * 完成采购
     * @param purchaseFinishedVo
     */
    @Override
    @Transactional
    public void done(PurchaseFinishedVo purchaseFinishedVo) {
        // 2.改变采购项状态
        boolean flag = true;
        List<PurchaseDetailEntity> purchaseDetailEntityList = new ArrayList<>(purchaseFinishedVo.getItems().size());
        for (PurchaseItemDoneVo item : purchaseFinishedVo.getItems()) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntity.setStatus(item.getStatus());

            // 采购完成，
            if (item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.FINISHED_STATUS.getCode())) {
                // 3.成功采购的要入库
                // 查询采购需求信息
                PurchaseDetailEntity purchaseDetail = purchaseDetailService.getById(item.getItemId());
                // 添加库存(skuid，仓库id，sku数量)
                wareSkuService.addStock(purchaseDetail.getSkuId(), purchaseDetail.getWareId(), purchaseDetail.getSkuNum());
            } else {
                // 有一个采购需求失败，采购单状态就不能完成
                flag = false;
            }
            purchaseDetailEntityList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        // 1.改变采购单状态
        Long purchaseId = purchaseFinishedVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);

        if (flag) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISHED_STATUS.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FAILED_STATUS.getCode());
        }
        baseMapper.updateById(purchaseEntity);
    }
}